package com.nsgf.library.ui.adapter;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.kunminx.binding_recyclerview.adapter.SimpleDataBindingAdapter;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.DutyManagerBean;
import com.nsgf.library.databinding.ItemPersonnelSelectionBinding;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 人员选择列表适配器
 */
public class PersonnelListAdapter extends SimpleDataBindingAdapter<DutyManagerBean.BuSchedulingListBean, ItemPersonnelSelectionBinding> {

    private List<Integer> preselectedIds;
    private OnItemClickListener onItemClickListener;
    // 使用Set来存储选中的id（接口返回的id字段，与传入的userId匹配）
    private Set<Integer> selectedIds;
    // 是否为单选模式（用于交班领导、值班领导、接班领导）
    private boolean isSingleSelectionMode = false;

    private static final DiffUtil.ItemCallback<DutyManagerBean.BuSchedulingListBean> diffCallback =
            new DiffUtil.ItemCallback<DutyManagerBean.BuSchedulingListBean>() {
                @Override
                public boolean areItemsTheSame(@NonNull DutyManagerBean.BuSchedulingListBean oldItem, @NonNull DutyManagerBean.BuSchedulingListBean newItem) {
                    // 使用rowCode作为唯一标识（如果rowCode为空则使用组合键）
                    String oldRowCode = oldItem.getRowCode();
                    String newRowCode = newItem.getRowCode();
                    if (oldRowCode != null && !oldRowCode.isEmpty() && newRowCode != null && !newRowCode.isEmpty()) {
                        return oldRowCode.equals(newRowCode);
                    }
                    // 回退使用userId+userName+realName组合
                    return oldItem.getUserId() == newItem.getUserId() &&
                           (oldItem.getUserName() != null ? oldItem.getUserName().equals(newItem.getUserName()) : newItem.getUserName() == null) &&
                           (oldItem.getRealName() != null ? oldItem.getRealName().equals(newItem.getRealName()) : newItem.getRealName() == null);
                }

                @Override
                public boolean areContentsTheSame(@NonNull DutyManagerBean.BuSchedulingListBean oldItem, @NonNull DutyManagerBean.BuSchedulingListBean newItem) {
                    // 只比较关键字段，选中状态在onBindItem中单独处理
                    String oldRowCode = oldItem.getRowCode();
                    String newRowCode = newItem.getRowCode();
                    if (oldRowCode != null && !oldRowCode.isEmpty() && newRowCode != null && !newRowCode.isEmpty()) {
                        return oldRowCode.equals(newRowCode) &&
                               (oldItem.getUserName() != null ? oldItem.getUserName().equals(newItem.getUserName()) : newItem.getUserName() == null) &&
                               oldItem.getIsLeader() == newItem.getIsLeader();
                    }
                    // 回退使用userId比较
                    return oldItem.getUserId() == newItem.getUserId() &&
                           (oldItem.getUserName() != null ? oldItem.getUserName().equals(newItem.getUserName()) : newItem.getUserName() == null) &&
                           oldItem.getIsLeader() == newItem.getIsLeader();
                }
                
                @Override
                public Object getChangePayload(@NonNull DutyManagerBean.BuSchedulingListBean oldItem, @NonNull DutyManagerBean.BuSchedulingListBean newItem) {
                    // 返回变化的内容，用于部分更新
                    return "update_selection";
                }
            };

    public PersonnelListAdapter(Context context,
                                 List<DutyManagerBean.BuSchedulingListBean> list,
                                 List<Integer> preselectedIds,
                                 OnItemClickListener listener) {
        super(context, R.layout.item_personnel_selection, diffCallback);
        this.preselectedIds = preselectedIds != null ? preselectedIds : new ArrayList<>();
        this.selectedIds = new HashSet<>();
        this.onItemClickListener = listener;
    }

    @Override
    protected void onBindItem(ItemPersonnelSelectionBinding binding, DutyManagerBean.BuSchedulingListBean item, RecyclerView.ViewHolder holder) {
        if (item == null) return;
        
        binding.setVm(item);

        // 判断是否被选中 - 每次都重新判断，确保准确性
        boolean isSelected = isItemSelected(item);

        // 强制更新图片资源，避免视图复用导致的状态错误
        // 先设置默认状态，再设置实际状态，确保刷新
        binding.checkbox.setImageResource(R.drawable.ic_chebox_false);
        if (isSelected) {
            binding.checkbox.setImageResource(R.drawable.ic_chebox_true);
        } else {
            binding.checkbox.setImageResource(R.drawable.ic_chebox_false);
        }

        // 先设置数据绑定的值（虽然布局中不再使用，但保持一致性）
        binding.setIsSelected(isSelected);
        
        // 执行绑定，确保数据绑定生效
        binding.executePendingBindings();
    }

    /**
     * 判断item是否被选中（根据接口返回的id字段）
     */
    private boolean isItemSelected(DutyManagerBean.BuSchedulingListBean item) {
        if (selectedIds == null || selectedIds.isEmpty() || item == null) {
            return false;
        }
        // 获取接口返回的id（Object类型，可能是Integer、Double或String）
        Object itemId = item.getId();
        if (itemId == null) {
            return false;
        }
        
        int idValue = 0;
        // 将id转换为整数（支持Integer、Double、String类型）
        if (itemId instanceof Integer) {
            idValue = (Integer) itemId;
        } else if (itemId instanceof Double) {
            idValue = ((Double) itemId).intValue();
        } else if (itemId instanceof String) {
            try {
                idValue = Integer.parseInt((String) itemId);
            } catch (NumberFormatException e) {
                return false;
            }
        }
        
        boolean result = idValue > 0 && selectedIds.contains(idValue);
        android.util.Log.d("PersonnelAdapter", "isItemSelected: id=" + itemId + " (value=" + idValue + "), result=" + result + ", selectedIds=" + selectedIds);
        return result;
    }
    
    /**
     * 获取当前选中的id集合
     */
    public Set<Integer> getSelectedIds() {
        return selectedIds != null ? new HashSet<>(selectedIds) : new HashSet<>();
    }

    /**
     * 更新选中的items - 提取id到Set中（接口返回的id字段）
     */
    public void updateSelectedItems(List<DutyManagerBean.BuSchedulingListBean> selectedItems) {
        android.util.Log.d("PersonnelAdapter", "updateSelectedItems called, selectedItems size: " + (selectedItems != null ? selectedItems.size() : 0));
        
        // 清空并重新填充selectedIds（使用接口返回的id字段）
        this.selectedIds.clear();
        if (selectedItems != null && !selectedItems.isEmpty()) {
            for (DutyManagerBean.BuSchedulingListBean item : selectedItems) {
                if (item != null) {
                    Object itemId = item.getId();
                    int userId = item.getUserId();
                    android.util.Log.d("PersonnelAdapter", "Processing item - userId: " + userId + ", id: " + itemId + " (type: " + (itemId != null ? itemId.getClass().getSimpleName() : "null") + ")");
                    
                    if (itemId != null) {
                        int idValue = 0;
                        // 将id转换为整数（支持Integer、Double、String类型）
                        if (itemId instanceof Integer) {
                            idValue = (Integer) itemId;
                        } else if (itemId instanceof Double) {
                            idValue = ((Double) itemId).intValue();
                        } else if (itemId instanceof String) {
                            try {
                                idValue = Integer.parseInt((String) itemId);
                            } catch (NumberFormatException e) {
                                android.util.Log.w("PersonnelAdapter", "Failed to parse id: " + itemId);
                                continue;
                            }
                        }
                        if (idValue > 0) {
                            this.selectedIds.add(idValue);
                            android.util.Log.d("PersonnelAdapter", "Added to selectedIds: " + idValue);
                        } else {
                            android.util.Log.w("PersonnelAdapter", "idValue is invalid: " + idValue);
                        }
                    } else {
                        android.util.Log.w("PersonnelAdapter", "itemId is null for userId: " + userId);
                    }
                }
            }
        }
        
        android.util.Log.d("PersonnelAdapter", "updateSelectedItems completed, selectedIds size: " + selectedIds.size() + ", selectedIds: " + selectedIds);
        
        // 刷新所有可见的item，不使用payload确保所有视图都刷新
        int itemCount = getItemCount();
        android.util.Log.d("PersonnelAdapter", "Item count: " + itemCount);
        if (itemCount > 0) {
            notifyItemRangeChanged(0, itemCount);
            android.util.Log.d("PersonnelAdapter", "Called notifyItemRangeChanged for range 0-" + itemCount);
        }
    }
    
    /**
     * 设置单选模式
     */
    public void setSingleSelectionMode(boolean isSingleSelectionMode) {
        this.isSingleSelectionMode = isSingleSelectionMode;
    }

    /**
     * 添加或移除选中的item（通过接口返回的id字段）
     */
    public void toggleSelection(DutyManagerBean.BuSchedulingListBean item) {
        if (item == null) return;
        
        // 获取接口返回的id（Object类型，可能是Integer、Double或String）
        Object itemId = item.getId();
        if (itemId == null) {
            android.util.Log.w("PersonnelAdapter", "toggleSelection: id is null");
            return;
        }
        
        int idValue = 0;
        // 将id转换为整数（支持Integer、Double、String类型）
        if (itemId instanceof Integer) {
            idValue = (Integer) itemId;
        } else if (itemId instanceof Double) {
            idValue = ((Double) itemId).intValue();
        } else if (itemId instanceof String) {
            try {
                idValue = Integer.parseInt((String) itemId);
            } catch (NumberFormatException e) {
                android.util.Log.w("PersonnelAdapter", "toggleSelection: id is invalid: " + itemId);
                return;
            }
        }
        
        if (idValue <= 0) {
            android.util.Log.w("PersonnelAdapter", "toggleSelection: id value is invalid: " + idValue);
            return;
        }
        
        boolean wasSelected = selectedIds.contains(idValue);
        
        if (isSingleSelectionMode) {
            // 单选模式：先清除所有选中项，然后选中当前项
            // 如果已经选中，保持选中状态（单选模式下不取消选中）
            if (!wasSelected) {
                selectedIds.clear();
                selectedIds.add(idValue);
            }
            // 如果已选中，不做任何操作（保持选中状态）
        } else {
            // 多选模式：切换选中状态
            if (wasSelected) {
                selectedIds.remove(idValue);
            } else {
                selectedIds.add(idValue);
            }
        }
        
        // 调试日志
        android.util.Log.d("PersonnelAdapter", "toggleSelection: isSingleMode=" + isSingleSelectionMode + ", id=" + itemId + " (value=" + idValue + "), wasSelected=" + wasSelected + ", now selectedIds=" + selectedIds);
        // 刷新所有可见的item，不使用payload确保所有视图都刷新
        int itemCount = getItemCount();
        if (itemCount > 0) {
            notifyItemRangeChanged(0, itemCount);
        }
    }

    public interface OnItemClickListener {
        void onItemClick(DutyManagerBean.BuSchedulingListBean item);
    }
}

